<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @package      FeatherPHP
 * @subpackage   Librairies
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://feather.portalier.com
 * @license      http://www.opensource.org/licenses/mit-license.php The MIT License
 */

class Dispatcher
{
	static function dispatch($url)
	{
		$controller = '';
		$action     = 'index';
		$params     = array(
			'bare'  => false,
			'admin' => false,
		);
		
		// routing
		$url = preg_replace(
			array_keys(Config::$routes),
			array_values(Config::$routes),
			$url
		);
		
		// parses url
		$args = explode('/', $url);
		foreach ($args as $i => $arg)
		{
			if (empty($arg) and strlen($arg) == 0)
				unset($args[$i]);
			elseif ($arg == 'bare')
			{
				$params['bare'] = true;
				unset($args[$i]);
			}
		}
		$args = array_values($args);
		
		if (!empty($args))
			$controller = array_shift($args);
		if (!empty($args))
			$action     = array_shift($args);
		$params['args'] =& $args;
		
		// controller
		require FEATHER.'libs'.DS.'loader.php';
		$load = Loader::instance('Loader');
		$load->libs('inflector', 'error');
		$controller = $load->controller($controller, $url, $action, $params);
		
		// action
		$controller->beforeAction();
		
		if (method_exists($controller, $action))
			call_user_func_array(array($controller, $action), $args);
		elseif (DEBUG)
			trigger_error(sprintf("Controller '%s' has no such action '%s'.", $controller->name, $action), E_USER_ERROR);
		elseif (DEBUG)
			Error::show(404);
		
		$controller->afterAction();
		
		// render
		if ($controller->autoRender) $controller->render();
	}
}
?>